/*
 * @Description:
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-11-19 11:57:27
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-20 17:44:22
 */
import { getToken, setToken } from '@/utils/token'
import { userInfo, role } from '@/api/login'
import { routerPermisson, listToTree } from '../rouerConfig.js'
const state = {
  token: getToken() || '',
  role: [],
  menuData: [],
  routes: [],
  addRoutes: []
}
const actions = {
  GET_USERINFO ({ commit }, data) {
    return new Promise(resolve => {
      // 获取用户信息
      userInfo().then(res => {
        if (res.code === '0') {
          const { rid } = res.data
          commit('SET_ROLE', [rid])
          resolve(res.data)
        }
        resolve({})
      })
    })
  },
  // 通过角色获取菜单
  GET_MENU_ByRole ({ commit }, data) {
    return new Promise(resolve => {
      role({ role: data }).then(res => {
        console.log(res, 'role')
        if (res.code === '0') {
          commit('SET_MENU_DATA', res.data)
          resolve(res.data)
        }
        resolve([])
      })
    })
  }
}
const mutations = {
  RESET_TOKEN (state) {
    state.token = ''
    setToken('')
  },
  SET_MENU_TOROUTES (state) {
    const target = [
      { path: '*', component: () => import('@/views/404/index.vue') }
    ]
    const routesData = [...state.addRoutes, ...target]
    state.routes = routesData
  },
  SET_MENU_DATA (state, data) {
    const baseRouter = routerPermisson(data)
    state.addRoutes = [baseRouter]
    state.menuData = listToTree(data, { pId: 'parentId' }, (v) => {
      if (!v.meta) {
        v.meta = {
          title: v.mName,
          icon: v.icon || ''
        }
      }
    })
    console.log(state.menuData, 'state.menuData')
  },
  SET_ROLE (state, rid) {
    state.role = rid
  },
  SET_TOKEN (state, { token }) {
    // setToken(data)
    state.token = token
    setToken(token)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
